package kr.hkit.androidcomplete03.ch28;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch28.common.Item;
import kr.hkit.androidcomplete03.ch28.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class DOMParser extends Activity {

	ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		list = (ListView) findViewById(R.id.orderListView);
		new ParsingXml().execute("order.xml");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {
		ProgressDialog progressDlg;

		@Override
		protected void onPreExecute() {
			Log.d("TAG", "DOMParser _ onPreExecute()");
			progressDlg = ProgressDialog.show(DOMParser.this, "Wait", "Xml Parsing...");
		}

		protected ArrayList<Item> doInBackground(String... params) {
			Log.d("TAG", "DOMParser _ doInBackground()");
			StringBuffer sb = new StringBuffer();
			BufferedReader br;
			String str = null;
			try {
				br = new BufferedReader(new InputStreamReader(
						openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());

		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			Log.d("TAG", "DOMParser _ onPostExecute()");
			MyAdapter adapter = new MyAdapter(getApplication(), R.layout.listrow, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
		}

	}

	public ArrayList<Item> parsingXml(String xml) {
		Log.d("TAG", "DOMParser _ parsingXml()");
		Log.d("XML Parsing", xml);
		ArrayList<Item> list = new ArrayList<>();
		Item item;
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try{
			DocumentBuilder builder = factory.newDocumentBuilder();
			InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
			Document doc = builder.parse(is);
			
			Element order = doc.getDocumentElement();
			NodeList items = order.getElementsByTagName("item");
			
			// order 하위 item 태그노드 방문
			for(int i=0; i<items.getLength(); i++){
				Item subItem = new Item();
				Node node = items.item(i);			// 하나의 item이 들어옴
				
				// <item Maker="Samsung" Price="23000">Mouse</item> 
				Node valueNode = node.getFirstChild(); 			// Mouse Node
				subItem.setItemName(valueNode.getNodeValue()); 	// Mouse
				
				NamedNodeMap attrs = node.getAttributes();
				// <item Maker="Samsung" Price="23000"> 속성 순회
				for(int j=0; j<attrs.getLength(); j++){
					Node attr = attrs.item(j);		// Price = "2300" or Maker = "Samsung"
					
					if(attr.getNodeName().equalsIgnoreCase("price")){
						subItem.setItemPrice(Integer.parseInt(attr.getNodeValue()));
					} else{
						subItem.setItemMaker(attr.getNodeValue());
					}
				}
				
				list.add(subItem);
			}
 		} catch(ParserConfigurationException e){
 			
 		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return list;
	}

}
